// pages/cart/cart.js
import {
  chooseAddress,openSetting,getSetting
} from '../../utils/asyncWX';
Page({

  data: {
    address:{},
    cartList:[],
    allChecked:false,
    totalPrice:0,
    totalNum:0,
  },

  onLoad(options) {
    
  },
  onShow(){
    var address = wx.getStorageSync("address");
    var cartList = wx.getStorageSync("cart") || [];
    // 使用every这个数组方法时，当数组为空数组时，返回值为true;
    // 所以先判断数组长度，再使用every这个方法
    // var allChecked = cartList.length>0?cartList.every((v) => v.checked):false;
    this.setData({
      address,
    })
    this.setCart(cartList);
  },
  // 获取收货地址
  // handleChooseAddress(){
    // 直接获取收货地址，第一次授权时会出现弹框，点击弹框中确定可获取用户的收货地址
    // 但是，点击取消时，在此点击授权就不会再触发弹框
    // wx.chooseAddress({
    //   success: (result)=>{
    //     console.log(result)        
    //   }
    // });
    // ----------------------------------------------------------
    // 正确步骤
    // 1、获取权限状态
      // authSetting中的scope.address的状态有三种，
        // 1  true       已授权获取收货地址
        // 2  false      未授权获取收货地址
        // 3  undefined  用户尚未点击取消或者确定
    //2 当这个值为true或者undefined的时候，都可用直接调用wx.chooseAddress方法获取收货地址
    //3 为false时，必须重新打开授权页面(wx.openSetting),把授权打开，在success的方法中继续调用wx.chooseAddress
    // wx.getSetting({
    //   success: (res)=>{
    //     let scopeAdress = res.authSetting["scope.address"];
    //     console.log(scopeAdress)
    //     if(scopeAdress==true || scopeAdress==undefined){
    //       wx.chooseAddress({
    //         success: (result1)=>{
    //           console.log(result1)        
    //         }
    //       });
    //     }else{
    //       wx.openSetting({
    //         success: (result2)=>{
    //           // console.log(result2)
    //           wx.chooseAddress({
    //             success: (result3) => {
    //               console.log(result3)
    //             }
    //           });
    //         },
    //       });
    //     }
    //   }
    // });


    // 封装过后的正确方法
    // getSetting().then(res=>{
    //   let scopeAdress = res.authSetting["scope.address"];
    //   if (scopeAdress == true || scopeAdress == undefined){
    //     chooseAddress().then(res1=>{
    //       console.log(res1)
    //     })
    //   }else{
    //     openSetting().then(res2=>{
    //       // console.log(res2)
    //       chooseAddress().then(res3=>{
    //         console.log(res3)
    //       })
    //     })
    //   }
    // })
  // }
  async handleChooseAddress(){
    // 获取授权中的收货地址授权
    try {
      let res1 = await getSetting();
      let scopeAdress = res1.authSetting["scope.address"];
      if (scopeAdress == true || scopeAdress == undefined) {
        let address = await chooseAddress();
        wx.setStorageSync("address", address);
      } else {
        await openSetting();
        let address = await chooseAddress();
        wx.setStorageSync("address", address);
      }
    } catch (error) {
      console.log(error)
    }
  },
  // 点击修改选中
  handleItemChecked(e){
    var goods_id = e.currentTarget.dataset.id;
    var cartList = this.data.cartList;
    var index=cartList.findIndex((item)=>{
      return item.goods_id==goods_id
    })
    cartList[index].checked = !cartList[index].checked;
    this.setCart(cartList);


  },
  // 封装了一些重用的代码段
  setCart(cartList) {
    var allChecked = true;
    var totalPrice = 0;
    var totalNum = 0;
    cartList.forEach(ele => {
      if (ele.checked) {
        totalPrice += ele.num * ele.goods_price;
        totalNum += ele.num
      } else {
        allChecked = false;
      }
    });
    allChecked = cartList.length > 0 ? allChecked : false
    this.setData({
      cartList,
      allChecked,
      totalPrice,
      totalNum
    });
    wx.setStorageSync("cart", cartList);
  },
  // 实现全选反选
  handleChangeAll(){
    var {allChecked,cartList}=this.data;
    allChecked=!allChecked;
    cartList.forEach(ele=>ele.checked=allChecked);
    this.setCart(cartList)
  },
  // 实现购物车数量加减
  handleItemEdit(e){
    let {id,payload}=e.currentTarget.dataset;
    let {cartList}=this.data;
    let index=cartList.findIndex(ele=>ele.goods_id==id);
    // 当购物车商品num为1并且点击-1时，触发删除的模态框，点击确定删除该商品，点击取消，什么都不做；
    if(cartList[index].num===1&&payload===-1){
      wx.showModal({
        title: '提示',
        content: '确定删除该商品吗？',
        success:(res)=> {
          if (res.confirm) {
            cartList.splice(index,1);
            this.setCart(cartList)
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    } else {
      cartList[index].num += payload
      this.setCart(cartList)
    }

    
  }
})